//
//  ZYIteratorImp.m
//  DesignMode
//
//  Created by wangzhipan on 2024/11/13.
//

#import "ZYIteratorImp.h"

@interface ZYIteratorImp()
@property (nonatomic, strong, nullable) NSMutableArray <id<IChannelExitLogic>>*logicList;
@end

@implementation ZYIteratorImp

- (instancetype)init
{
    if (self = [super init]) {
        self.logicList = [NSMutableArray array];
    }
    return self;
}

- (void)push:(nonnull id<IChannelExitLogic>)logic
{
    if (!logic) {
        return;
    }
    [self.logicList addObject:logic];
}

- (void)remove:(nonnull id<IChannelExitLogic>)logic
{
    if (!logic) {
        return;
    }
    [self.logicList removeObject:logic];
}

- (void)removeAll
{
    [self.logicList removeAllObjects];
}


- (nullable id<IChannelExitLogic>)checkWhoToExecute
{
    NSArray <id<IChannelExitLogic>> *sortedList = [self.logicList sortedArrayUsingComparator:^NSComparisonResult(id<IChannelExitLogic> obj1, id<IChannelExitLogic> obj2) {
        return obj1.priority - obj2.priority;
    }];
    id<IChannelExitLogic> result = nil;
    for (id<IChannelExitLogic> logic in sortedList) {
        if (logic.enableExecute) {
            logic.executeBlock ? logic.executeBlock() : nil;
            result = logic;
            break;
        }
    }
    return result;
}
@end
